import fs from 'fs';
import { fromMarkdown } from 'mdast-util-from-markdown';

const markdown = fs.readFileSync('./CHANGELOG.md', 'utf-8');
const extractText = node => node.children?.map(child => child.value).join('') || '';

const parseListItem = listItem =>
  listItem.children.reduce(
    (itemDetails, part) => {
      if (part.type === 'paragraph') {
        part.children.forEach(element => {
          switch (element.type) {
            case 'text':
              itemDetails.title += element.value;
              break;
            case 'link':
              itemDetails.link = element.url;
              itemDetails.author = extractText(element);
              break;
            case 'image':
              itemDetails.url = element.url;
              break;
          }
        });
      } else if (part.type === 'list') {
        itemDetails.desc = part.children.map(descItem => {
          console.log('extractText(descItem.children[0]) ---->',extractText(descItem.children[0]));
          return extractText(descItem.children[0]);
        });
      }
      return itemDetails;
    },
    { title: '', desc: [], url: '', link: '', author: '' }
  );

const parseList = listNode => listNode.children.map(parseListItem);

const parseMarkdown = markdown => {
  const ast = fromMarkdown(markdown);
  const info = { version: '', time: '', fns: [] };

  ast.children.forEach((node, index) => {
    if (node.type === 'heading') {
      if (node.depth === 2) {
        const [version, time] = node.children[0].value.match(/V\d+\.\d+\.\d+|\d{4}\.\d+\.\d+/g);
        info.version = version || '';
        info.time = time || '';
      } else if (node.depth === 3) {
        const title = node.children[0].value;
        const nextNode = ast.children[index + 1];
        const lists = nextNode && nextNode.type === 'list' ? parseList(nextNode) : [];
        info.fns.push({ title, lists });
      }
    }
  });

  return info;
};

const main = () => {
  const info = parseMarkdown(markdown);
  console.log(info);
  fs.writeFileSync('./sdfsd.json', JSON.stringify(info, null, 2));
};

main();
